package cn.hyh;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hyh
 * 2020/6/3
 */
public class ListUtil {

    /**
     * 数组深拷贝
     *
     * @param source 原数组
     * @param <T>    实体
     * @return 新数组
     */
    public static <T> List<T> deepCopy(List<T> source) {
        List<T> result = new ArrayList<>();
        if (source == null || source.size() == 0) {
            return result;
        }
        if (!(source.get(0) instanceof Serializable)) {
            throw new RuntimeException("系统错误: 拷贝数组内实体类应实现序列化接口");
        }
        try {
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(byteOut);
            out.writeObject(source);
            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            ObjectInputStream in = new ObjectInputStream(byteIn);
            result = (List<T>) in.readObject();
        } catch (Exception e) {
            throw new RuntimeException("系统错误: 数组拷贝失败");
        }
        return result;
    }
}
